﻿using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Linq;

namespace BlazorSample
{
    public class JsonHelper
    {
        public static JSchema GenerateSchema(JToken token)
        {
            JSchema schema = new JSchema();
            switch (token.Type)
            {
                case JTokenType.Object:
                    schema.Type = JSchemaType.Object;
                    var requiredProperties = new List<string>();
                    foreach (var property in token.Children<JProperty>())
                    {
                        var propertySchema = GenerateSchema(property.Value);
                        schema.Properties[property.Name] = propertySchema;
                        if (property.Value.Type != JTokenType.Null) // 假设非null属性是必需的
                        {
                            schema.Required.Add(property.Name);
                        }
                    }
                    break;
                case JTokenType.Array:
                    schema.Type = JSchemaType.Array;
                    foreach (var item in token)
                    {
                        var itemSchema = GenerateSchema(item);
                        schema.Items.Add(itemSchema);
                    }
                    break;
                case JTokenType.String:
                    schema.Type = JSchemaType.String;
                    break;
                case JTokenType.Integer:
                    schema.Type = JSchemaType.Integer;
                    break;
                case JTokenType.Float:
                    schema.Type = JSchemaType.Number;
                    break;
                case JTokenType.Boolean:
                    schema.Type = JSchemaType.Boolean;
                    break;
                case JTokenType.Null:
                    schema.Type = JSchemaType.Null;
                    break;
                default:
                    schema.Type = JSchemaType.Object;
                    break;
            }
            return schema;
        }
    }
}
